<template>
    <div class="centre f16">
        <div class="tab pb-5">
            <div class="flex jc-e mb-5">
                <el-button plain @click="add">New</el-button>
                <el-button plain @click="save">Save</el-button>
                <el-button type="primary" @click="open()" plain>Add to Order</el-button>
                <el-button type="primary" @click="AddToQuotation" plain>Add to Quotation</el-button>
                <el-button type="primary" @click="del">Delete</el-button>
            </div>

            <p class="fwb fa5">RFQ DETAIL {{ rfqId }} of {{ centerTable.length - 1 }} Quoted</p>
            <!-- 表格 -->
            <el-table :data="centerTable" @cell-click="table" @cell-mouse-enter="hover" :row-class-name="rfqList"
                height="50.5vh" @selection-change="row" style="width: 100%">
                <el-table-column type="selection"  width="30" />
                <el-table-column label="MODEL" min-width="200">
                    <template v-slot="model">
                        <el-select v-model="model.row.product.model" @change="chModel" @input="getModel"
                            @visible-change="visible" filterable placeholder="MODEL">
                            <el-option v-for="item in newModel" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="BRAND" min-width="130">
                    <template v-slot="brand">
                        <el-select v-model="brand.row.brand.brand_name" @input="getBrand" @visible-change="visible"
                            filterable placeholder="BRAND">
                            <el-option v-for="item in newBrand" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="BUYER" min-width="170">
                    <template v-slot="buyer">
                        <!-- <el-select v-model="buyer.row.purchaser_array" @remove-tag="delBuyer" @visible-change="getBuyer" collapse-tags
                            collapse-tags-tooltip placeholder="BUYER" multiple>
                            <el-option v-for="item in newBuyer" :key="item.label" :label="item.label"
                                :value="item.id" />
                        </el-select> -->
                        <el-select v-model="buyer.row.purchaser_id_list" @remove-tag="delBuyer" 
                            @visible-change="getBuyer" collapse-tags collapse-tags-tooltip placeholder="BUYER" multiple>
                            <el-option v-for="item in newBuyer" :key="item.id" :label="item.label" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="QTY" min-width="80">
                    <template v-slot="qty">
                        <el-input v-model="qty.row.Qty" placeholder="QTY" />
                    </template>
                </el-table-column>
                <el-table-column label="PRICE" min-width="80">
                    <template v-slot="price">
                        <el-input v-model="price.row.item.purchase_price" placeholder="PRICE" />
                    </template>
                </el-table-column>
                <el-table-column label="LEADING" min-width="120">
                    <template v-slot="leading">
                        <el-select v-model="leading.row.item.leadingtime" filterable placeholder="LEADING">
                            <el-option v-for="item in newLeading" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="CONDITION" min-width="150">
                    <template v-slot="condition">
                        <el-select v-model="condition.row.item.product_condition" filterable placeholder="CONDITION">
                            <el-option v-for="item in newCondition" :key="item.label" :label="item.label"
                                :value="item.case" />
                        </el-select>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 图表 -->
        <div ref="main" class="w100p mt-10 br pt-5 main" style="height: 33vh"></div>

        <!-- 添加订单弹窗 -->
        <AddOrderVue ref="AddOrder" :newLeading="newLeading" :newCondition="newCondition"></AddOrderVue>

        <!-- 添加到报价弹窗 -->
        <AddQuotationVue ref="AddQuotation" @quote="quote" :newLeading="newLeading" :newCondition="newCondition">
        </AddQuotationVue>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import AddOrderVue from "./components/AddOrder.vue";
import AddQuotationVue from "./components/AddQuotation.vue";
import { ElMessage } from 'element-plus'
import * as $axios from '../../../api/index'
//  按需引入 echarts
import * as echarts from "echarts";
// import westeros from 'echarts/theme/westeros'
import { useDemoStore } from '../../../pinia/index'
const store = useDemoStore()

const props = defineProps({
    rfqId: Number
})

onMounted(() => {
    getBuyer() //触发getBuyer事件把采购id变成采购名
})

// 表格数据
const centerTable = ref([])
const product = () => {
    // console.log(props)
    const data = {
        token: store.token,
        id: props.rfqId
    }
    $axios.$Product(data).then(res => {
        centerTable.value = res.data.data
        // centerTable.value[0].purchaser_array = 123
        product_id.value = centerTable.value[0] && centerTable.value[0].product_id  //图表id
        model.value = centerTable.value[0] && centerTable.value[0].product.model   //图表标题
        figure() //触发获取图表数据的事件
        centerTable.value.push({
            "Qty": '',
            "product": {

            },
            "purchaser_array": {

            },
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
            }
        })
    })
}

// 监听属性
watch(props, () => {
    product()
})

// model选项框
const chModel = () => {
    const length = centerTable.value[centerTable.value.length - 1].product.model
    // 判断最后一个model框有没有值，有就新增一条空的输入框
    if (length) {
        centerTable.value.push({
            "Qty": '',
            "product": {

            },
            "purchaser_array": {

            },
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
            }
        })
    }
}

// 删除采购
const delBuyer = (p) => {
    console.log(p)
    const name = array.value.map(item => {
        return item.id
    })
    const index = name.indexOf(p)
    const data = {
        token: store.token,
        inquiry_item_info_id: array.value[index].inquiry_item_info_id
    }
    $axios.$pollingDel(data).then(res => {
        array.value.splice(index, 1)
        // emits('del')
        // console.log(res.Status)
        // ElMessage({
        //     message: 'successfully delete',
        //     type: 'success',
        // })
    })
}


// table 鼠标经过时触发的
const array = ref([])
const hover = (data) => {
    array.value = data.purchaser_array
}

// 复选框
const InquiryOfId = ref([])   //询盘id
const row = (data) => {
    // console.log(data)
    InquiryOfId.value = []
    data.forEach(item => {
        if (item.product.model) {
            item.purchaser_array.forEach(id => {
                InquiryOfId.value.push(id.inquiry_item_info_id)
                // console.log(id.inquiry_item_info_id)
            })
        }
    })

    console.log(InquiryOfId.value)
}

// 点击表格
const product_id = ref('') //图表数据
const inquiry_item_info_id = ref('')
const model = ref('') //图表标题
const table = (data) => {
    // console.log(data)
    product_id.value = data.product_id
    inquiry_item_info_id.value = data.inquiry_item_info_id
    model.value = data.product.model
    figure()
    init()
    console.log(data)
}

// 表格高亮
const rfqList = ({
    row,
    rowIndex,
}) => {
    // console.log(inquiry_item_info_id.value)
    if (row.product_id === product_id.value) {
        return 'success-row'
    }
    return ''
}

const visible = () => {
    inpModel.value = '',
        inpBrand.value = ''
}

// model
const newModel = ref([])
const inpModel = ref('')
var timer
const getModel = (text) => {
    if (text.data != null) {
        inpModel.value += text.data
    } else if (text.data == null) {
        inpModel.value = inpModel.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpModel.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
    $axios.$product_find(data).then(res => {
        console.log(res.data)
        newModel.value = res.data.map(item => {
            return {
                'label': item.model,
                'id': item.product_id
            }
        })
    })
},300)
}

// brand
const newBrand = ref([])
const inpBrand = ref('')
var timer
const getBrand = (text) => {
    if (text.data != null) {
        inpBrand.value += text.data
    } else if (text.data == null) {
        inpBrand.value = inpBrand.value.slice(0, -1)
    }
    const data = {
        token: store.token,
        keywords: inpBrand.value
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
    $axios.$product_brand(data).then(res => {
        console.log(res.data)
        newBrand.value = res.data.map(item => {
            return {
                'label': item.brand_name,
                'id': item.brand_id
            }
        })
    })
},300)
    console.log(inpBrand.value)
}

//Buyer(获取销售与采购人员列表)
const newBuyer = ref([])
const getBuyer = () => {
    const data = {
        token: store.token,
        keywords: '采购'
    }
    $axios.$userUser_list(data).then(res => {
        newBuyer.value = res.data.map(item => {
            return {
                'label': item.name,
                'id': item.id
            }
        })
    })
}


// Leading
const newLeading = [
    {
        case: "一周有效",
        label: "+1 week"
    },
    {
        case: "三个月有效",
        label: "+3 mouth"
    },
    {
        case: "今天有效",
        label: "+1 day"
    },
    {
        case: "三天有效",
        label: "+3 day"
    },
    {
        case: "五天有效",
        label: "+5 day"
    },
    {
        case: "一个月有效",
        label: "+1 mouth"
    },
    {
        case: "半年有效",
        label: "+6 mouth"
    },
]

// Condition(状态)
const newCondition = [
    {
        case: "QB全新保内",
        label: "New Sealed Under Guarantee"
    },
    {
        case: "QG全新过保",
        label: "New Sealed Beyond Guarantee"
    },
    {
        case: "QK全新开封保内",
        label: "New Unsealed Under Guarantee"
    },
    {
        case: "QKG全新开封过保",
        label: "New Unsealed Beyond Guarantee"
    },
    {
        case: "F翻新",
        label: "Refurbish"
    },
    {
        case: "E二手",
        label: "Used"
    },
    {
        case: "J兼容",
        label: "Substitute"
    },
    {
        case: "G高仿无牌",
        label: "High Copy Blank Brand"
    },
    {
        case: "GD高仿带牌",
        label: "High Copy With Brand"
    },
    {
        case: "S升级",
        label: "Upgrade"
    },
    {
        case: "W无货",
        label: "Discontinued"
    }
]

// 新增
const add = () => {
    save()
    centerTable.value = []
    for (let i = 0; i <= 5; i++) {
        centerTable.value.push({
            "Qty": '',
            "inquiry_id": '',
            "msg":1,
            "product": {
            },
            "purchaser_array": {

            },
            "brand": {
                "brand_name": "",
                "filter": "",
            },
            "item": {
                "leadingtime": "",
            }
        })
    }
    console.log(centerTable.value)
}


// save 保存
const save = () => {
    const arr = ref([])
    const newArr = ref([])
    centerTable.value.forEach((items) => {
        // 判断是否有model有就是要进行提交的
        if (items.product.model) {
            if (items.purchaser_array.length == items.purchaser_id_list.length && items.purchaser_array.length > 0) {  //没有修改
                items.purchaser_array.forEach((name) => {
                    items.inquiry_item_info_id = name.inquiry_item_info_id
                    arr.value.push({
                        ...items,
                        id: name.id
                    })
                    newArr.value = arr.value.map(item => {
                        return {
                            "product_id": typeof item.product.model != 'string' ? item.product.model : item.product.product_id,
                            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
                            "inquiry_id": item.inquiry_id,
                            "purchaser_id": item.id,
                            "inquiry_item_info_id": item.inquiry_item_info_id,
                            'model': item.product.model,
                            'brand': item.brand.brand_name,
                            'qty': item.Qty,
                            'purchase_price': item.item.purchase_price,
                            'leadingtime': item.item.leadingtime,
                            'product_condition': item.item.product_condition || '',
                            "risk": "稳妥",
                            "Effective": "三天有效",
                            "Reliability": "牢靠"
                        }
                    })
                })
            } else { //有修改
                // console.log(2)
                items.purchaser_id_list.forEach((name,index) => {
                    // console.log(items.purchaser_array[index]&&items.purchaser_array[index].id)
                    arr.value.push({
                        ...items,
                        id:name,
                        inquiry_item_info_id: items.purchaser_array[index]&&items.purchaser_array[index].inquiry_item_info_id
                    })
                    // console.log(arr.value)

                    newArr.value = arr.value.map(item => {
                        return {
                            "product_id": typeof item.product.model != 'string' ? item.product.model : item.product.product_id,
                            "brand_id": typeof item.brand.brand_name == 'string' ? item.brand.brand_id : item.brand.brand_name,
                            "inquiry_id": item.inquiry_id||'',
                            "purchaser_id": item.id,
                            "inquiry_item_info_id": item.inquiry_item_info_id||'',
                            'model': item.product.model,
                            'brand': item.brand.brand_name,
                            'qty': item.Qty,
                            'purchase_price': item.item.purchase_price,
                            'leadingtime': item.item.leadingtime,
                            'product_condition': item.item.product_condition || '',
                            "risk": "稳妥",
                            "Effective": "三天有效",
                            "Reliability": "牢靠"
                        }
                    })
                })
            }
        }
    });

    // console.log(newArr.value[0].inquiry_id)
    console.log(newArr.value)
    // console.log(props.rfqId)

    const data = {
        "product": newArr.value,
        'token': store.token,
        "customer_id": 5,
        "inquiry_id": centerTable.value[0].msg == 1 ?'':props.rfqId
    }
    $axios.$add(data).then(res => {
        console.log(res)
        if (res.Status == 0) {
            centerTable.value[0].msg == 1 && emits('save')   //是新增就调用这个方法
            centerTable.value[0].msg == 1 || product()
            ElMessage({
                message: 'Successful preservation',
                type: 'success',
            })
        } else {
            ElMessage.error('Save the error')
        }
    })

}

// 新增订单转询盘后触发该事件，然后更新页面
const quote = () => {
    emits('save')
}

const emits = defineEmits(['save'])

// 删除
const del = () => {
    // console.log(InquiryOfId.value)
    if (InquiryOfId.value && InquiryOfId.value.length > 0) {
        const data = {
            token: store.token,
            inquiry_item_info_id: InquiryOfId.value
        }
        $axios.$pollingDel(data).then(res => {
            product()
            ElMessage({
                message: 'successfully delete',
                type: 'success',
            })
            console.log(res)
        })
    } else {
        ElMessage({
            message: 'Please choose',
            type: 'warning',
        })
    }
}

// 图表数据
const figureData = ref([])
const figure = () => {
    const data = {
        token: store.token,
        product_id: product_id.value
    }
    $axios.$offer(data).then(res => {
        // console.log(res.data)
        figureData.value = res.data
        init()
    })
}

// 暴露方法
defineExpose({
    product,
})

// 添加订单弹窗
const AddOrder = ref()
const open = () => {
    AddOrder.value.open()
}

// 添加到报价弹窗
const AddQuotation = ref()
const AddToQuotation = () => {
    AddQuotation.value.poseQuotation()
}


// 多选框
const handleSelectionChange = (data) => {
    console.log(data)
}


const main = ref() // 使用ref创建虚拟DOM引用，使用时用main.value

// 图表数据
var myChart
const init = () => {
    if (myChart != null && myChart != "" && myChart != undefined) {
        myChart.dispose();//销毁
    }
    myChart = echarts.init(main.value, 'westeros');

    var option = {
        title: {
            text: model.value
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#fff'
                }
            }
        },
        legend: {
            data: ['Historical inquiry']
        },
        toolbox: {
            feature: {
                saveAsImage: {}
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                boundaryGap: false,
                data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: 'Historical inquiry',
                type: 'line',
                stack: 'Total',
                areaStyle: {},
                emphasis: {
                    focus: 'series'
                },
                data: figureData.value
            }
        ]
    };
    option && myChart.setOption(option);
    window.addEventListener("resize", myChart.resize) //自动缩放

}


</script>

<style lang="less" scoped>
@import '../rfq.less';
</style>